#include "aky_com_include.h"

s_time_t g_s_time = {0};
volatile s_flag_group_t g_s_flag_group = {0};
volatile s_flag_group_const_t g_s_flag_group_const = {0};

code uint8_t MonthDay[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 1	 2	 3 	 4 	 5 	 6 	 7 	 8 	 9	 10	 11	 12

#define aky_timer_reload_cnt 65535 - 41
// 周期定时器初始化
void aky_timer_init(void)
{
    TCF2 = 0;
    TC2C = 65536 - 328; // 10ms
    TC2R = 65536 - 328; //
    TC2M = 0xF8;
    IEN2 |= 0x08;

#if (AKY_DEBUG_UART_PRINTF == 1)
    aky_uart_send_string("aky_timer_init\n");
#endif
}


// 周期定时器中断处理
void aky_timer_it_pro(void)
{
    TCF2 = 0;
    aky_delay_tick_incre_pro();
    key_scan();
    get_sdadc_val_pro();
    charge_stat_detect_pro();
    uart_cmd_decode();
    timer_base_pro();
    
}

// rtc初始化
void aky_rtc_init(void)
{
    g_s_time.year = MIN_YEAR;
    g_s_time.month = MONTH_INIT;
    g_s_time.day = DAY_INIT;
    g_s_time.hour = HOUR_INIT;
    g_s_time.min = MIN_INIT;

    T0M |= 0X01; // T0TB = 1,Clock source must from 32768 Hz X’tal
    // Timer interrupt is occur when 0.5SEC overflow.
    /* 60s Interrupt function */
    // T0M |= 0X02; // T0MOD = 1,Timer interrupt is occur when 60SEC overflow.
    // "SEC" = 00H~3BH(0~59)
    IEN0 |= 0x02; // T0IEN = 1
    T0M |= 0XF0; // T0ENB = 1

#if (AKY_DEBUG_UART_PRINTF == 1)
    aky_uart_send_string("aky_rtc_init\n");
#endif
}

// rtc 中断处理
void aky_rtc_it_pro(void)
{
    uint8_t MDay = 0;
    static uint8_t half_sec_cnt = 0;
    static uint8_t sec_cnt = 0;

	TF0 = 0;//CLR IT FLAG
    g_s_flag_group.flag_rtc_it_trig = 1;
    half_sec_cnt++;
    if (half_sec_cnt >= 2)
    {
        half_sec_cnt = 0;
        sec_cnt++;
        if (sec_cnt >= 60)
        {
            sec_cnt = 0;
            g_s_time.min++;//软件rtc
            if (g_s_time.min > 59)
            {
                g_s_time.min = 0;
            	g_s_time.hour++;
            	if (g_s_time.hour > 23)
            	{
            		g_s_time.hour = 0;
            		g_s_time.day++;
            		MDay = MonthDay[g_s_time.month-1];
            		if (g_s_time.month ==2)
            		{
            			if (YEAR0 == 0 && YEAR1 == 0) MDay = 29;
            		}
                    if (g_s_time.day > MDay || g_s_time.day == 0)//等于0则溢出 5bit
            		{
            			g_s_time.day = 1;
            			g_s_time.month++;
            			if (g_s_time.month > 12)
            			{
            				g_s_time.month = 1;
            				g_s_time.year++;
            				if (g_s_time.year > MAX_YEAR) g_s_time.year = MIN_YEAR;
            			}
            		}
            	}
            }
        } 
    }
    

    #if (AKY_DEBUG_UART_PRINTF == 1)
        // aky_uart_send_byte(0x55);
    #endif
}
